package com.example.demo810.cfg;

/**
 * @author lzh
 * @date 2020/8/10 - 10:28
 */

import com.alibaba.fastjson.JSONObject;
import com.example.demo810.po.JwtProperties;
import com.example.demo810.po.SecurityUser;
import com.example.demo810.po.SysUser;
import com.example.demo810.util.JwtUtils;
import com.example.demo810.util.RedisUtils;
import com.example.demo810.vo.AjaxResponse;
import com.example.demo810.vo.LoginReq;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证用户名密码正确后，生成一个token，并将token返回给客户端
 * 该类继承自UsernamePasswordAuthenticationFilter，重写了其中的2个方法 ,
 * attemptAuthentication：接收并解析用户凭证。
 * successfulAuthentication：用户成功登录后，这个方法会被调用，我们在这个方法里生成token并返回。
 *
 * @author admin
 */
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final JwtUtils jwtUtils;

    private final JwtProperties jwtProperties;


    private final RedisUtils redisUtils;


    private final AuthenticationManager authenticationManager;

    public AuthenticationFilter(AuthenticationManager authenticationManager
            , JwtUtils jwtUtils, JwtProperties jwtProperties, RedisUtils redisUtils) {
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
        this.jwtProperties = jwtProperties;
        this.redisUtils = redisUtils;

        //spring security 默认有1套自己的登录实现流程，这里不需要自己写login接口，而是使用默认的Spring security登录成功/失败的处理
        super.setFilterProcessesUrl("/login");
    }


    /**
     * spring security 默认登录接口的起点，从这里接收Request
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {



        // 从post body输入流中获取到登录的信息
        try {
            LoginReq loginReq = new ObjectMapper().readValue(request.getInputStream(), LoginReq.class);

            //登录时先校对验证码
            String verifyKey = "captcha_" + loginReq.getUuid();
            String verificationCodeIn = redisUtils.getValue(verifyKey);
            redisUtils.delete(verifyKey);
//            String verificationCodeIn = (String) request.getSession().getAttribute("verificationCode");
//            request.getSession().removeAttribute("verificationCode");

            if (StringUtils.isEmpty(verificationCodeIn) || !verificationCodeIn.equals(loginReq.getVerificationCode())) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msg", "验证码错误,登录失败!");
                jsonObject.put("code", 9999);
                response.getWriter().write(jsonObject.toJSONString());
                response.flushBuffer();
                return null;
            }


            //再由springSecurity校对用户名/密码，最后返回token
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginReq.getUsername(), loginReq.getPassword())
            );
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 成功验证后调用的方法
    // 如果验证成功，就生成token并返回
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException {

        SecurityUser jwtUser = (SecurityUser) authResult.getPrincipal();
        System.out.println("jwtUser:" + jwtUser.toString());
        String token = jwtUtils.createToken(jwtUser.getUsername());
        String key = jwtProperties.header + "_" + jwtUser.getUsername();
        redisUtils.setValue(key, token, 1000 * 60 * jwtProperties.expire);


        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("token", token);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("username", jwtUser.getUsername());
        jsonObject.put("authorities", jwtUser.getAuthorities());
        jsonObject.put("msg", "登录成功");
        jsonObject.put("token", token);
        response.getWriter().write(jsonObject.toJSONString());
        response.flushBuffer();

    }

    //登录失败后的处理流程
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 401);
        jsonObject.put("msg", "认证失败," + failed.getMessage());


        response.getWriter().write(jsonObject.toJSONString());
        response.setContentType("application/json;charset=UTF-8");
        response.flushBuffer();

    }
}

